package org.csu.small.service.impl;



import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import org.csu.small.common.Constant;
import org.csu.small.common.UniformResponse;
import org.csu.small.entity.Cart;
import org.csu.small.entity.Product;
import org.csu.small.persistence.CartMapper;
import org.csu.small.persistence.ProductMapper;
import org.csu.small.service.ICartService;
import org.csu.small.utils.BigDecimalUtil;
import org.csu.small.utils.PropertiesUtil;
import org.csu.small.vo.CartProductVO;
import org.csu.small.vo.CartVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class CartServiceImpl implements ICartService {

    @Autowired
    private CartMapper cartMapper;

    @Autowired
    private ProductMapper productMapper;


    @Override
    public UniformResponse<CartVO> add(Integer userId, Integer productId, Integer quantity) {

        Cart cart = cartMapper.selectOne(Wrappers.<Cart>query().eq("user_id",userId).eq("product_id",productId));
        Product product = productMapper.selectOne(Wrappers.<Product>query().eq("id",productId));
        int rows = cartMapper.selectCount(Wrappers.<Cart>query().eq("user_id",userId).eq("product_id",productId));
        if(rows != 0){
            //有该商品则只修改数量
            cart.setQuantity(cart.getQuantity()+quantity);
            cart.setChecked(Constant.Cart.CHECKED);
            cart.setUpdateTime(LocalDateTime.now());
            int updatecount = cartMapper.updateById(cart);
            if(updatecount == 0){
                return UniformResponse.createForErrorMessage("添加失败");
            }
        }else{
            //没有商品则新增商品到购物车
            Cart newcart = new Cart();
            newcart.setUserId(userId);
            newcart.setProductId(productId);
            newcart.setQuantity(quantity);
            newcart.setChecked(Constant.Cart.CHECKED);
            newcart.setAddPrice(product.getPrice());
            newcart.setCreateTime(LocalDateTime.now());
            newcart.setUpdateTime(LocalDateTime.now());
            int insertcount = cartMapper.insert(newcart);
            if (insertcount == 0){
                return UniformResponse.createForErrorMessage("添加失败");
            }
        }
        CartVO cartVO = getCartVOLimit(userId);
        return UniformResponse.createForSuccess(cartVO);
    }

    @Override
    public UniformResponse<CartVO> updateCartNum(Integer userId, Integer productId, Integer quantity) {
        Cart cart = cartMapper.selectOne(Wrappers.<Cart>query().eq("user_id",userId).eq("product_id",productId));
        int rows = cartMapper.selectCount(Wrappers.<Cart>query().eq("user_id",userId).eq("product_id",productId));
        if(rows == 0){
            return UniformResponse.createForErrorMessage("请选择购物车中的商品");
        }else{
            cart.setQuantity(quantity);
            cart.setChecked(Constant.Cart.CHECKED);
            cart.setUpdateTime(LocalDateTime.now());
            int updatecount = cartMapper.updateById(cart);

            if(updatecount == 0){
                return UniformResponse.createForErrorMessage("更新失败");
            }
            CartVO cartVO = getCartVOLimit(userId);
            return UniformResponse.createForSuccess(cartVO);
        }
    }

    @Override
    public UniformResponse<CartVO> deleteByProductIds(Integer userId, String productIds) {
        List<String> productIdList = Splitter.on(",").splitToList(productIds);

        if(CollectionUtils.isNotEmpty(productIdList)){
            for(String productId : productIdList){
                Integer iproductId = Integer.valueOf(productId);
                int rows = cartMapper.selectCount(Wrappers.<Cart>query().eq("user_id",userId).eq("product_id",iproductId));
                if(rows != 0){
                    QueryWrapper<Cart> query = new QueryWrapper<>();
                    query.eq("user_id",userId).eq("product_id",iproductId);
                    cartMapper.delete(query);
                }
            }
        }else {
            return UniformResponse.createForSuccessMessage("请选择商品");
        }
        CartVO cartVO = getCartVOLimit(userId);
        return UniformResponse.createForSuccess(cartVO);
    }


    @Override
    public UniformResponse<CartVO> selectOrUnSelect(Integer userId, Integer productId, Integer status){
        if (productId == null){
            Cart cart = cartMapper.selectOne(Wrappers.<Cart>query().eq("user_id",userId).eq("product_id",productId));
        }
        Cart cart = cartMapper.selectOne(Wrappers.<Cart>query().eq("user_id",userId).eq("product_id",productId));
        int rows = cartMapper.selectCount(Wrappers.<Cart>query().eq("user_id",userId).eq("product_id",productId));
        if(rows != 0){
            cart.setChecked(status);
            cart.setUpdateTime(LocalDateTime.now());
            int updatecount = cartMapper.updateById(cart);
            if(updatecount == 0){
                return UniformResponse.createForErrorMessage("选择或取消选择失败");
            }
        }
        CartVO cartVO = getCartVOLimit(userId);
        return UniformResponse.createForSuccess(cartVO);
    }

    @Override
    public UniformResponse<CartVO> selectOrUnSelectAll(Integer userId, Integer status){
        List<Cart> cartList= cartMapper.selectList(Wrappers.<Cart>query().eq("user_id",userId));
        //int rows = cartMapper.selectCount(Wrappers.<Cart>query().eq("user_id",userId));
        if(CollectionUtils.isNotEmpty(cartList)){
            for(Cart cartItem : cartList){
                cartItem.setChecked(status);
                cartItem.setUpdateTime(LocalDateTime.now());
                cartMapper.updateById(cartItem);
            }
        }
        CartVO cartVO = getCartVOLimit(userId);
        return UniformResponse.createForSuccess(cartVO);
    }

    @Override
    public UniformResponse<CartVO> getCartList(Integer userId){
        CartVO cartVO = getCartVOLimit(userId);
        return UniformResponse.createForSuccess(cartVO);
    }

    @Override
    public UniformResponse<Integer> getCartProductCount(Integer userId){
        List<Cart> cartList= cartMapper.selectList(Wrappers.<Cart>query().eq("user_id",userId));
        Integer count = 0;
        if(CollectionUtils.isNotEmpty(cartList)){
            for(Cart cartItem : cartList){
                count = count+cartItem.getQuantity();
            }
        }
        return UniformResponse.createForSuccess(count);
    }



    private CartVO getCartVOLimit(Integer userId){
        CartVO cartVO = new CartVO();

        BigDecimal cartTotalPrice = new BigDecimal("0");

        //获取该用户的购物车列表
        QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);

        List<Cart> cartList = cartMapper.selectList(queryWrapper);



        List<CartProductVO> cartProductVOList = Lists.newArrayList();

        if(CollectionUtils.isNotEmpty(cartList)){
            for(Cart cartItem : cartList){
                CartProductVO cartProductVO = new CartProductVO();
                cartProductVO.setId(cartItem.getId());
                cartProductVO.setUserId(cartItem.getUserId());
                cartProductVO.setProductId(cartItem.getProductId());

                Product product = productMapper.selectById(cartItem.getProductId());

                if(product != null){
                    cartProductVO.setProductMainImage(product.getMainImage());
                    cartProductVO.setProductName(product.getName());
                    cartProductVO.setProductSubtitle(product.getSubtitle());
                    cartProductVO.setProductStatus(product.getStatus());
                    cartProductVO.setProductPrice(product.getPrice());
                    cartProductVO.setProductStock(product.getStock());
                    cartProductVO.setAddPrice(cartItem.getAddPrice());


                    int buyLimitCount = 0;

                    if(product.getStock() >= cartItem.getQuantity()){
                        buyLimitCount = cartItem.getQuantity();
                        cartProductVO.setLimitQuantity(Constant.Cart.LIMIT_NUM_SUCCESS);
                    }else{
                        buyLimitCount = product.getStock();
                        cartProductVO.setLimitQuantity(Constant.Cart.LIMIT_NUM_FAILURE);

                        Cart cartForQuantity = new Cart();
                        cartForQuantity.setId(cartItem.getId());
                        cartForQuantity.setQuantity(buyLimitCount);
                        int rows = cartMapper.updateById(cartForQuantity);
                    }
                    cartProductVO.setQuantity(buyLimitCount);
                    cartProductVO.setProductTotalPrice(BigDecimalUtil.mul(product.getPrice().doubleValue(),cartProductVO.getQuantity()));
                    cartProductVO.setProductChecked(cartItem.getChecked());
                }
                if(cartItem.getChecked() == Constant.Cart.CHECKED){
                    cartTotalPrice = BigDecimalUtil.add(cartTotalPrice.doubleValue(),cartProductVO.getProductTotalPrice().doubleValue());
                }
                cartProductVOList.add(cartProductVO);
            }
            cartVO.setCartTotalPrice(cartTotalPrice);
            cartVO.setCartProductVOList(cartProductVOList);
            cartVO.setAllChecked(this.getAllCheckedStatus(userId));
            cartVO.setImageHost(PropertiesUtil.getProperty("image.server.url"));
        }
        return cartVO;
    }

    /**
     * 是否全选
     * @param userId
     * @return
     */
    private boolean getAllCheckedStatus(Integer userId){
        if(userId == null){
            return false;
        }
        QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(("user_id"),userId);
        queryWrapper.eq("checked",Constant.Cart.UN_CHECKED);
        int result = cartMapper.selectCount(queryWrapper);
        return result == 0;
    }

}
